package com.brian.mqconsumer.service;

import com.alibaba.fastjson.JSONObject;
import com.brian.mqconsumer.entity.DispatchEntity;
import com.brian.mqconsumer.mapper.DispatchMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @program: architect 派单服务
 * @author: Brian Huang
 * @create: 2019-07-17 20
 **/
@Service
public class DispatchConsumerService {

    @Autowired
    private DispatchMapper dispatchMapper;

  @RabbitListener(queues = "order_dic_queue")
  public void  process(Message message, @Headers Map<String, Object> headers, Channel channel) throws IOException {
      String messageId = message.getMessageProperties().getMessageId();
      String msg = new String(message.getBody(), "UTF-8");
      System.out.println("派单服务平台接口的到消息: " + msg + " ,消息id: " + messageId);
      JSONObject jsonObject = (JSONObject) JSONObject.parse(msg);
      String orderId = (String) jsonObject.get("orderId");

      if(StringUtils.isEmpty(orderId)){
          //记录到日志
          return;
      }
      DispatchEntity dispatchEntity = new DispatchEntity();
      // 订单id
      dispatchEntity.setOrderId(orderId);
      // 外卖员id
      dispatchEntity.setTakeoutUserId(1212312321l);
      // 外卖路线
      dispatchEntity.setDispatchRoute("130.87,40.654");

      DispatchEntity save = null;
      try {
          save = dispatchMapper.save(dispatchEntity);
          if(save != null){
              //消息入库成功后，手动通知服务器端删除该消息
              channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
          }
      } catch (Exception e) {
          e.printStackTrace();
          //丢弃该消息
          channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
      }



  }
}
